//////////////////////////////////////////////////////////////////////////////////
//	Copyright 2011 by Yosef Grabivker, ryuho@homenetworksoft.com
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////
// Default search implementation searchimpl.h
#ifndef _SEARCH_IMPL_YG_H__
#define _SEARCH_IMPL_YG_H__ 

#include "def.h"
#include <wx/listctrl.h>

template<class T> struct CSearchImpl: public ISearchProvider
{
	CSearchImpl(T& own, wxListCtrl* pListPtr=NULL):m_clsOwner(own), m_lSearchResLine(SEARCH_NOT_FOUND), m_pListPtr(pListPtr)
	{
		if ( m_pListPtr )
		{
			m_idCtrl = m_pListPtr->GetId();
		}

		m_attrSelected.SetBackgroundColour( wxColor(255,255,0) );
	}

	void								ResetSearchPos()
	{
		m_lSearchResLine = SEARCH_NOT_FOUND;
	}

	void								SetSearchListPtr(wxListCtrl* pListPtr)
	{
		m_pListPtr = pListPtr;

		if ( m_pListPtr )
		{
			m_idCtrl = m_pListPtr->GetId();
		}
	}

	virtual	int							Search(const wxString& val, unsigned int iFieldID, size_t posStart)
	{
		int nRes(SEARCH_NOT_FOUND);

		if ( m_pListPtr )
		{
			SEARCHFIELD* sf;
			size_t sz=0;
			m_clsOwner.GetSearchFields(sf, sz);

			for ( long l=posStart;l<m_clsOwner.GetItemCount(m_idCtrl);l++)
			{
				for (size_t i=0;i<sz;i++)
				{
					if ( i==iFieldID || iFieldID==SEARCH_FIELD_ANY )
					{
						wxString str = m_clsOwner.GetItemText(l, i, m_idCtrl);

						if ( str.Matches(val) || wxNOT_FOUND !=str.Find(val) )
						{
							long lOld = m_lSearchResLine;
							m_lSearchResLine = l;

							m_pListPtr->RefreshItem( lOld );

							m_pListPtr->EnsureVisible(l);
							m_pListPtr->RefreshItem( l );

							return	(int)l;
						}
					}
				}
			}
		}

		return nRes;
	}

	class wxListItemAttr*		GetItemAttr(long item, wxWindowID id=wxID_ANY)
	{
		if ( m_lSearchResLine==item )
		{
			return &m_attrSelected;
		}

		return NULL;
	}

private:
	T&							m_clsOwner;
	int							m_idCtrl;
	long						m_lSearchResLine;
	class wxListCtrl*			m_pListPtr;
	wxListItemAttr				m_attrSelected;
};

#endif // _SEARCH_IMPL_YG_H__